package com.dl.mall.controller.admin;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dl.mall.annotation.MethodInfo;
import com.dl.mall.config.satoken.StpAdminUtil;
import com.dl.mall.entity.Page;
import com.dl.mall.entity.admin.Admin;
import com.dl.mall.service.admin.AdminService;
import com.dl.mall.utils.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author DL
 * @create 2022-03-29 15:38
 */
@Slf4j
@RestController()
@RequestMapping("/admin")
@Api(tags="管理员controller")
public class AdminController {

    @Resource
    AdminService adminService;

    @ApiOperation(value="注销",notes="注销")
    @GetMapping("/logout")
    public Result logout(){
        // 当前会话注销登录
        StpAdminUtil.logout();
        return Result.ok();
    }

    @ApiOperation(value="每次路由跳转都会触发该方法，返回用户信息")
    @GetMapping("/info")
    public Result info(){
        List<String> roleList = StpAdminUtil.getRoleList(StpAdminUtil.getLoginIdAsString());
        log.info("{}", roleList);
        if (roleList != null){
            return Result.ok().data("roles", roleList);
        }else {
            return Result.error("失败");
        }
    }

    @ApiOperation(value="管理员登录")
    @PostMapping("/login")
    public Result login(@RequestBody JSONObject jsonObject){
        log.info("{}",jsonObject);
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");

        Admin admin = adminService.login(username);// 调用服务层登录方法
        log.info("admin:{}", admin);

        if (admin != null){//判断账号密码
            if (admin.getState() == 0){
                return Result.error("账号锁定，请联系管理员");
            }
            // 使用 md5 + salt 校验，salt=用户id
            String md5BySalt = SaSecureUtil.md5BySalt(password, admin.getUserId());

            if (md5BySalt.equals(admin.getPassword())){
                StpAdminUtil.login(admin.getUserId(), "PC");
                log.info("StpAdminUtil.getTokenInfo:{}", StpAdminUtil.getTokenInfo());
                log.info("StpAdminUtil.getTokenName:{}", StpAdminUtil.getTokenName());

                //登录成功
                return Result.success("登录成功")
                        .data(StpAdminUtil.getTokenName(), StpAdminUtil.getTokenValue())
                        .data("name", admin.getName());
            }
            return Result.error("密码错误");
        }else {
            return Result.error("用户名不存在");
        }
    }


    @ApiOperation(value="添加管理员查重")
    @GetMapping("/getAdminByUsername")
    public Result getAdminByUsername(String username){
        Admin admin = adminService.getAdminByUsername(username);
        if (admin == null){
            return Result.ok();
        }else {
            return Result.no("管理员username重复");
        }
    }

    @ApiOperation(value="添加管理员")
    @PostMapping("/addAdmin")
    public Result addAdmin(@RequestBody JSONObject jsonObject){
        boolean addAdmin = adminService.addAdmin(jsonObject);
        if (addAdmin){
            return Result.ok();
        }else {
            return Result.error("失败");
        }
    }

    @ApiOperation(value="根据 userId 查询管理员信息")
    @GetMapping("/getAdminInfo")
    private Result getAdminInfo(String userId) {
        System.out.println("userId = " + userId);
        Admin adminInfo = adminService.getAdminInfoById(userId);
        if (adminInfo != null){
            return Result.ok("成功").data("user", adminInfo);
        }else {
            return Result.error("失败");
        }
    }

    @ApiOperation(value="修改管理员账号状态")
    @GetMapping("/modifyAdminState")
    private Result modifyAdminState(String userId, Integer state) {
        boolean modifyAdminState = adminService.modifyAdminState(userId, state);
        if (modifyAdminState){
            return Result.ok("成功");
        }else {
            return Result.error("失败");
        }
    }

    @ApiOperation(value="修改管理员角色")
    @PostMapping("/modifyAdminRole")
    private Result modifyAdminRole1(@RequestBody JSONObject jsonObject) {
        JSONObject modifyRoleForm = jsonObject.getJSONObject("modifyRoleForm");
        String userId = modifyRoleForm.getString("userId");
        JSONArray roleIdList = modifyRoleForm.getJSONArray("roleIdList");
        boolean modifyUserRole = adminService.modifyAdminRole(userId, roleIdList);
        if (modifyUserRole){
            return Result.ok("成功");
        }else {
            return Result.error("失败");
        }
    }

    @ApiOperation(value="重置管理员账号密码为123")
    @GetMapping("/resetPassword")
    private Result resetPassword(String userId) {
        String resetPassword = adminService.resetPassword(userId);
        if (resetPassword != null){
            return Result.ok("成功").data("resetPassword", resetPassword);
        }else {
            return Result.error("失败");
        }
    }

    @ApiOperation(value="修改管理员账号密码")
    @GetMapping("/modifyPassword")
    private Result modifyPassword(String password, String newPassword) {
        String userId = StpAdminUtil.getLoginIdAsString();
        Admin admin = adminService.getAdminInfoById(userId);
        String dbPassword = admin.getPassword();
        String md5BySalt = SaSecureUtil.md5BySalt(password, userId);
        if (dbPassword.equals(md5BySalt)){
            boolean modifyPassword = adminService.modifyPassword(userId, newPassword);
            if (modifyPassword){
                return Result.ok("成功");
            }else {
                return Result.no("失败");
            }
        }
        return Result.no("失败，原密码错误！");
    }

    @ApiOperation(value="修改管理员账号信息")
    @PostMapping("/modifyAdminInfo")
    private Result modifyAdminInfo(@RequestBody JSONObject jsonObject) {
        boolean modifyAdminInfo = adminService.modifyAdminInfo(jsonObject);
        if (modifyAdminInfo){
            return Result.ok("成功");
        }else {
            return Result.error("失败");
        }
    }

    @ApiOperation(value="根据 条件 查询管理员列表",notes="根据 条件 查询管理员列表")
    @PostMapping("/adminList")
    public Result getUserList1(@RequestBody JSONObject jsonObject){
        System.out.println("jsonObject = " + jsonObject);
        JSONObject condition = jsonObject.getJSONObject("condition");

        Page<Admin> page = adminService.getAdminByCondition(condition);
        if (page != null){
            return Result.ok("成功").data("page", page);
        }else {
            return Result.error("失败");
        }
    }

}
